package com.atguigu.gmall.mq.receiver;

import com.atguigu.gmall.mq.config.DeadLetterMqConfig;
import com.atguigu.gmall.mq.config.DelayedMqConfig;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

//监听器
@Component
public class ConfirmReceiver {

    //  监听消息
    //  @SneakyThrows @Data 类似都是底层封装好的.
    //  设置  exchange.confirm ---> routing.confirm ----> queue.confirm
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "queue.confirm", durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = "exchange.confirm"),
            key = {"routing.confirm"}
    ))
    public void getMsg(String msg, Message message, Channel channel) {
        //获取发送过来的数据
        System.out.println(msg);
        System.out.println("消息主体: " + new String(message.getBody()));
        //  消息确认 第一个参数表示 消息中的表示 ，第二个参数表示 是否批量确认 false: 一次只确认一个，true：表示批量确认.
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //  监听延迟消息： DeadLetterMqConfig 类中设置好了绑定关系
    @RabbitListener(queues = DeadLetterMqConfig.queue_dead_2)
    public void getDelayMsg(String msg, Message message, Channel channel) {
     //设置时间格式
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(msg);
        System.out.println("接收时间："+simpleDateFormat.format(new Date()));

        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //  监听消息.
    @RabbitListener(queues = DelayedMqConfig.queue_delay_1)
    public void getDelay(String msg,Message message, Channel channel){
        //设置时间格式
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(msg);
        System.out.println("接收时间："+simpleDateFormat.format(new Date()));
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
